// 定义上下文菜单
const contextMenus = [
  { id: 'page-qrcode', title: '当前页面链接' },
  {
    id: 'selection-qrcode',
    title: '“%s”',
    contexts: ['selection'],
  },
  {
    id: 'link-qrcode',
    title: '选中链接',
    contexts: ['link'],
  },
];

// 创建上下文菜单
contextMenus.map(({ id = '', type = 'normal', title = '', contexts = ['page'] }) => {
  title = `生成二维码 » ${title}`;
  chrome.contextMenus.create({
    id,
    type,
    title,
    contexts,
    documentUrlPatterns: ['<all_urls>'],
  });
});

// 监听上下文菜单点击事件
chrome.contextMenus.onClicked.addListener(({ menuItemId, pageUrl, selectionText, linkUrl }) => {
  let qrcode = menuItemId === 'page-qrcode' ? pageUrl : linkUrl || selectionText || '';
  try {
    qrcode = encodeURIComponent(qrcode);
  } catch (err) {}
  chrome.tabs.create({
    url: `chrome-extension://${chrome.runtime.id}/html/popup.html?qrcode=${qrcode}`,
    selected: true,
  });
});
